package com.fallsvc.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @auther falls_vc
 * description:
 * @date 2025/9/21  10:35
 */
@Slf4j
public class RedisUtil {

    private final String REDIS_SPLIT = ":";
    private final String REDIS_DEFAULT_PREFIX = "default";
    private StringRedisTemplate stringRedisTemplate;

    public RedisUtil(StringRedisTemplate stringRedisTemplate) {
      this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * redis get
     *
     * @param key
     * @return
     */
    public String get(String key) {
        try{
            return key == null ? null : stringRedisTemplate.opsForValue().get(key);
        }catch (Exception e) {
            log.error("redis get key error!key:{},e:",key,e);
            return null;
        }
    }

    /**
     * Redis hasKey
     * true 存在   false不存在
     *
     * @param key
     * @return
     */
    public Boolean hasKey(String key) {
        try {
            return key == null ? false : stringRedisTemplate.hasKey(key);
        }catch (Exception e) {
            log.error("redis hasKey key error!key:{},e:",key,e);
            return false;
        }
    }

    /**
     * Redis set
     *
     * @param key
     * @param value
     * @return
     */
    public Boolean set(String key,String value) {
        try{
            if(!StringUtils.hasText(key) || !StringUtils.hasText(value)) {
                return false;
            }
            stringRedisTemplate.opsForValue().set(key,value);
            return true;
        } catch (Exception e) {
            log.error("redis set key error!key:{},e:",key,e);
            return false;
        }
    }

    /**
     * redis set
     * 设置过期时间-单位秒
     * @param key
     * @param value
     * @param timeout
     * @return
     */
    public Boolean set(String key,String value, Long timeout) {
        try{
            if(!StringUtils.hasText(key) || !StringUtils.hasText(value)
                    || timeout < 0) {
                return false;
            }
            stringRedisTemplate.opsForValue().set(key,value,timeout, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.error("redis set key error!key:{},e:",key,e);
            return false;
        }
    }

    public String buildKey(String user_prefix, String... args) {
        if(user_prefix == null ) {
            user_prefix = REDIS_DEFAULT_PREFIX;
        }
        StringBuilder key = new StringBuilder();
        key.append(user_prefix);
        if (args != null) {
            for(String arg : args) {
                key.append(REDIS_SPLIT).append(arg);
            }
        }
        return key.toString();
    }
}
